<template>
  <div class="fileUpload">
    <uploader
      :file-status-text="fileStatusText"
      ref="uploader"
      :options="options"
      :autoStart="false"
      @file-added="onFileAdded"
      @file-progress="onFileProgress"
      @file-success="onFileSuccess"
      @file-error="onFileError"
      class="uploader-example">

      <uploader-unsupport></uploader-unsupport>
      <uploader-drop>
        <p>拖拽文件至此或点击按钮</p>
        <uploader-btn>选择文件</uploader-btn>
        <uploader-btn :directory="true" :multiple="true">上传文件夹</uploader-btn>
      </uploader-drop>
      <uploader-list></uploader-list>
    </uploader>

    <!--    <input-->
    <!--      class="hidden"-->
    <!--      type="file"-->
    <!--      ref="file"-->

    <!--      webkitdirectory-->
    <!--    />-->
  </div>
</template>

<script>

import SparkMD5 from 'spark-md5';
import md5 from 'js-md5';

export default {
  name: 'FileUpload',
  computed: {
    // Uploader	上传组件实例
    uploaderInstance() {
      return this.$refs.uploader.uploader
    }
  },
  data() {
    return {
      options: {
        target: 'http://localhost:18989/fileUpload',
        chunkSize: 5 * 1024 * 1024,
        //并发上传数
        simultaneousUploads: 1,
      },
      attrs: {
        accept: 'video/*'
      },
      statusTextMap: {
        success: '成功了',
        error: '出错了',
        uploading: '上传中',
        paused: '暂停中',
        waiting: '等待中',
        cmd5: '校验中'
      },
      params:{
        filePath:"/",
        isDir:0
      },
      fileStatusText: (status, response) => {
        return this.statusTextMap[status];
      },
    }
  },
  methods: {
    onFileAdded(file) {
      // 计算MD5
      this.computeMD5(file);
    },
    //计算MD5
    computeMD5: function (file) {
      this.statusTextMap.paused = "校验中...";
      //文件状态为“计算md5...”
      file.cmd5 = true
      let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
        chunkSize = 2 * 1024 * 1024, //2MB
        chunks = Math.ceil(file.size / chunkSize),
        currentChunk = 0,
        spark = new SparkMD5.ArrayBuffer(),
        fileReader = new FileReader();

      let time = new Date().getTime();

      fileReader.onload = (e) => {
        // 将自定义参数直接加载uploader实例的opts上
        Object.assign(this.uploaderInstance.opts, {
          query: {
            ...this.params
          }
        })

        spark.append(e.target.result);
        currentChunk++;

        if (currentChunk < chunks) {
          console.log(`第${currentChunk}分片解析完成, 开始第${currentChunk + 1} / ${chunks}分片解析`);
          loadNext();
        } else {
          console.log('文件加载完毕');
          let fileMd5 = spark.end(); //得到md5

          let hexMd5 = md5(fileMd5 + file.fileType);

          console.log(`MD5计算完成：${file.name} \nMD5：${fileMd5} \n分片：${chunks} 大小:${file.size} 用时：${new Date().getTime() - time} ms`);
          console.log("加密后:" + hexMd5)


          spark.destroy(); //释放缓存
          file.uniqueIdentifier = hexMd5; //将文件md5赋值给文件唯一标识
          file.cmd5 = false; //取消计算md5状态
          file.resume(); //开始上传
        }
      };

      fileReader.onerror = () => {
        console.warn('onerror:哎呀！出事了.');
        file.cancel();
      };

      let loadNext = () => {
        let start = currentChunk * chunkSize,
          end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;

        fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end));
      };
      loadNext();
    },
    // 文件进度的回调
    onFileProgress(rootFile, file, chunk) {
      console.log(`上传中 ${file.name}，chunk：${chunk.startByte / 1024 / 1024} ~ ${chunk.endByte / 1024 / 1024}`)
    },
    onFileSuccess(rootFile, file, response, chunk) {
      console.log(response)
      let resp = JSON.parse(response);
      if (resp.data === 200) {
        console.log('上传成功，不需要合并');
      }
    },

    onFileError(rootFile, file, response, chunk) {
      console.log('Error:', response)
    },
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
}

.uploader-list > ul > li {
  width: 100%;
  color: red;
  margin-bottom: 0;
}

a {
  color: #42b983;
}


</style>
